/**
 * 
 */
package mblog.web.controller.desk.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mblog.base.data.Data;
import mblog.base.utils.GeoIps;
import mblog.base.utils.IpAdrressUtil;
import mblog.base.utils.MailHelper;
import mblog.base.utils.NeteaseSendCode;
import mblog.core.data.AccountProfile;
import mblog.core.data.Addresses;
import mblog.core.persist.service.AddressesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import mblog.base.lang.Consts;
import mblog.core.data.User;
import mblog.core.persist.service.UserService;
import mblog.core.persist.service.VerifyService;
import mblog.web.controller.BaseController;
import mblog.web.controller.desk.Views;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @author mark
 *
 */
@Controller
@RequestMapping("/user")
public class ProfileController extends BaseController {
	@Autowired
	private UserService userService;
	@Autowired
	private VerifyService verifyService;
	@Autowired
	private MailHelper mailHelper;
	@Autowired
	private AddressesService addressesService;

	public void initAddress(ModelMap model,String province,String city,String location){
		List<Addresses> dataList = addressesService.findByParentId("1");

		List<Addresses> twoList = new ArrayList<>();
		if(StringUtils.isNotEmpty(province)){
			twoList = addressesService.findByParentId(province);
		}else{
			twoList = addressesService.findByParentId(String.valueOf(dataList.get(0).getId()));
		}

		List<Addresses> threeList = new ArrayList<>();
		if(StringUtils.isNotEmpty(province)){
			threeList = addressesService.findByParentId(city);
		}else{
			threeList = addressesService.findByParentId(String.valueOf(twoList.get(0).getId()));
		}

		model.put("cityList", dataList);
		model.put("twoList", twoList);
		model.put("threeList", threeList);
	}


	@RequestMapping(value = "/profile", method = RequestMethod.GET)
	public String view(ModelMap model, HttpServletRequest request) {
		AccountProfile profile = getSubject().getProfile();
		User view = userService.get(profile.getId());
//		String realIp = IpAdrressUtil.getIpAdrress(request);
//		try {
//			Map<String,String> dataMap = GeoIps.getLocationInfoByIp(realIp);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		initAddress(model,view.getProvince(),view.getCity(),view.getLocation());

		model.put("view", view);
		return view(Views.USER_PROFILE);
	}

	@RequestMapping(value = "/profile", method = RequestMethod.POST)
	public String post(String name, String signature,String address,String province,String city,String location,String mobile,String valideCode, ModelMap model) {
		boolean bl = false;
		try {
			bl = NeteaseSendCode.checkCode(mobile,valideCode);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Data data;
		AccountProfile profile = getSubject().getProfile();
		StringBuffer message = new StringBuffer("操作成功");
		try {
			User user = new User();
			user.setId(profile.getId());
			user.setName(name);
			user.setSignature(signature);
			user.setProvince(province);
			user.setCity(city);
			user.setLocation(location);
			user.setAddress(address);
			if(bl){
				user.setMobile(mobile);
			}else{
				message.append("手机号码错误");
			}

			putProfile(userService.update(user));

			// put 最新信息
			User view = userService.get(profile.getId());

			initAddress(model,view.getProvince(),view.getCity(),view.getLocation());

			model.put("view", view);

			data = Data.success(message.toString(), Data.NOOP);
		} catch (Exception e) {
			data = Data.failure(e.getMessage());
		}


		model.put("data", data);
		return view(Views.USER_PROFILE);
	}

	@RequestMapping(value = "/email", method = RequestMethod.GET)
	public String email() {
		return view(Views.USER_EMAIL);
	}

	@RequestMapping(value = "/email", method = RequestMethod.POST)
	public String emailPost(String email, ModelMap model) {
		Data data;
		AccountProfile profile = getSubject().getProfile();

		try {
			Assert.notNull(email, "缺少必要的参数");

			// 先执行修改，判断邮箱是否更改，或邮箱是否被人使用
			userService.updateEmail(profile.getId(), email);

			String code = verifyService.generateCode(profile.getId(), Consts.VERIFY_BIND, email);

			Map<String, Object> context = new HashMap<>();
			context.put("userId", profile.getId());
			context.put("code", code);
			context.put("type", Consts.VERIFY_BIND);

			mailHelper.sendEmail(Consts.EMAIL_TEMPLATE_BIND, email, "邮箱绑定验证", context);

			data = Data.success("操作成功，已经发送验证邮件，请前往邮箱验证", Data.NOOP);
		} catch (Exception e) {
			data = Data.failure(e.getMessage());
		}
		model.put("data", data);
		return view(Views.USER_EMAIL);
	}
}
